<?php
	
	$db = $this->puzzle->PDM->default_container;
	
	// Check if the user is logged in
	
	if (isset($_SESSION['login_token']))
	{
		$token = unserialize($_SESSION['login_token']);
		
		if ($token->username != "")
		{
			$login = true;
		}
		else
		{
			$login = false;
		}
	}
	
	// If it is not, check the cookies
	
	if ($login == false)
	{
		$username = $_COOKIE['username'];
		$date_start = $_COOKIE['date_start'];
		$secret = $_COOKIE['secret'];
		
		$u = $db->listEntity("user", "username='$username'")->elements[0];
		
		if ($u != null)
		{
			// Expected secret
			$seed = $u->id . $u->username . $u->password . $date_start;
			$expected_secret = strtoupper(sha1($seed));
			
			// If cookie secret equals the expected...
			if ($secret == $expected_secret)
			{
				// Create login token
				$token->user = $u;
				$token->date_start = date("Y-m-d H:i:s");
				$_SESSION['login_token'] = serialize($token);
			
				$login = true;
			}
			else
			{
				// If not, eliminate session data and cookies
				
				$_SESSION['login_token'] = null;
				
				setcookie("user", "", time() - 3600);
				setcookie("dstart", "", time() - 3600);
				setcookie("secret", "", time() - 3600);
			}
		}
	}
	
	// Generate response
	
	$view_return = $this->puzzle->PVM->createView("element", "php-puzzle-xml");
	$view_return->params->name = "return";
	$view_return->params->attributes = array('name' => 'result', 'value' => 'ok');
	$view_return->params->content = "OK";
	
	$view_response = $this->puzzle->PVM->createView("puzzle-response", "php-puzzle-bigbang");
	$view_response->params->elements[] = $view_return;
?>
